#encoding: utf-8
class Frontend::LibraryController < ApplicationController
  def index
    ### search for document, forward to lend
    if params[:search_key].nil?
      @documents = LibraryDocument.order(sort_column(LibraryDocument) + " " + sort_direction).where('status > 0').page(params[:page]).per(15)
    else
      key = params[:search_key]
      @documents = LibraryDocument.where("title LIKE '%#{key}%' OR summary LIKE '%#{key}%' OR tags LIKE '%#{key}%' OR author LIKE '%#{key}%' OR isbn LIKE '%#{key}%' AND status > 0").page(params[:page]).per(15)
    end
  end

  def borrowlist
    #display borrowed documents of one user
    if params[:user_id].nil?
      flash[:alert] = "Lỗi không tìm thấy thông tin"
      redirect_to_library
    else
      @borrow_list = LibraryBorrowRecord.joins(:student,:library_document).where('library_borrow_records.student_id = ' + params[:user_id].to_s).page(params[:page]).per(15)
      if @borrow_list.first.nil?
        flash[:alert] = "Lỗi không tìm thấy thông tin"
        redirect_to_library
      end
    end
  end

  def view
    #view single document info
    selected = LibraryDocument.column_names - ["category_id", "id"]
    @document = LibraryDocument.find_by_id(params[:document_id], :select => selected )
    if @document.nil?
      render('frontend/portal/404')
    end
  end

  def redirect_to_library
    redirect_to :controller => "backend/library", :action => "index"
  end

end
